#!/bin/sh
### BEGIN INIT INFO
# Provides:          rpimonitor-helper
# Required-Start:    $remote_fs $syslog
# Required-Stop:     $remote_fs $syslog
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# X-Interactive:     true
# Short-Description: RPi-Monitor sunxi-temp helper
# Description:       RPi-Monitor helper daemon for providing cpustats, Vcore and disk temperature
### END INIT INFO

# Source function library.
. /lib/lsb/init-functions

DAEMON="/usr/local/sbin/rpimonitor-helper.sh"
PIDFILE="/var/run/rpimonitor-helper.pid"

[ -x $DAEMON ] || exit 0

checkroot(){
  if [ "$(id -u)" != "0" ]; then
    echo "This script must be run as root"
    exit 1
  fi
}

start() {
  touch $PIDFILE

  for pid in $(cat $PIDFILE); do
     if ( kill -0 $pid > /dev/null 2>&1 ); then
      echo "RPi-Monitor helper is already running.";
      status;
      return 0;
    fi
  done;

  log_daemon_msg "Starting RPi-Monitor helper" "rpimonitor-helper"
  nice -n 19 $DAEMON $PIDFILE &
  status=$?
  log_end_msg $status
}

stop() {
  touch $PIDFILE
  log_daemon_msg "Stopping RPi-Monitor helper" "rpimonitor-helper"
  for pid in $(cat $PIDFILE); do
    kill -15 $pid > /dev/null 2>&1
  done
  status=$?
  log_end_msg $status
  rm $PIDFILE
}

restart() {
  stop
  sleep 2
  start
}

status(){
  echo -n "RPi-Monitor helper status: "
  if [ ! -f $PIDFILE ]; then
    echo "Not running"
    exit 0
  fi
  for pid in $(cat $PIDFILE); do
    kill -0 $pid > /dev/null 2>&1 && echo -n "[ \033[1;32mok\033[0m ]" || echo -n "[\033[31mFAIL\033[0m]";
  done;
  echo
}

checkroot
case "$1" in
  start)
    start
  ;;
  stop)
    stop
  ;;
  status)
    status
  ;;
  restart)
    restart
  ;;
  *)
    echo "Usage: $0 {start|stop|restart|status}"
  ;;
esac

exit 0
